<?php if (defined("YTDJ") or die()); 

Class YouTube {
	
	function getVideos($q, $startindex, $maxresults) {	
		$result = Array();
		
		// add clip keyword?
		if (Config::getInstance()->addClipKeywordToQueries) { $q .= ' clip'; }
		
		// get feed
		$feed = new YouTubeFeedList($q, $startindex, $maxresults);

		// loop entries
		foreach ($feed->entries as $entry) {
			
			$video = new Video($entry["id"], $entry);
			$result[$entry["id"]] = $video;
		}
				
		return $result;
	}
	
	/**
	 * getVideo
	 *
	 * @param string $id
	 * @param boolean $updateExtended
	 * @return Video
	 */
	function getVideo($id, $updateExtended = false) {
		// get feed
		$feed = new YouTubeFeedDetail($id);
		
		$video = new Video($id, $feed->title);
		if (!$video->hasRecord() || $updateExtended) {
			$video->set("title", $feed->title);
			$video->set("thumbnail", $feed->thumbnail);
			$video->set("duration", gmdate("H:i:s", $feed->duration));
			$video->set("rating", $feed->rating);
		}
		
		return $video;
	}
	
	function extractSimpleMetadata($entrytitle) {
		foreach(self::getTitleSeperators() as $seperator) {
			$dashpos = strpos($entrytitle, rtrim($seperator, "\r\n"));
			if ($dashpos !== false) {
				$artist = trim(substr($entrytitle, 0, $dashpos));
				if (!$artist) {
					$artist = trim($entrytitle);
				} else {
					$title = trim(substr($entrytitle, $dashpos+1, strlen($entrytitle)-$dashpos));
					break;
				}
			}			
		}
		return array("artist" => $artist, "title" => $title);
	}
	
	function getTitleSeperators() {
		return file("config/youtubeseperators.txt", FILE_IGNORE_NEW_LINES);
	}

}

?>